# -*- coding: utf-8 -*-
import pickle
from datetime import datetime
from app.configs import global_config
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import sessionmaker
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy import Float
from sqlalchemy import LargeBinary
from sqlalchemy import DateTime

name, db = global_config['name'], global_config['db']
if name == "urd":
    engine = create_engine(db, encoding='utf-8', echo=False, pool_size=20, max_overflow=50)
else:
    engine = create_engine(db, encoding='utf-8', echo=False)


meta = MetaData(bind=engine)
Base = declarative_base(bind=engine)
db_session = sessionmaker(bind=engine)


def clear_db():
    Base.metadata.drop_all()
    Base.metadata.create_all()


def integer(index=False, default=None, comment=''):
    return Column(Integer, index=index, default=default, comment=comment)


def float(index=False, default=None, comment=''):
    return Column(Float, index=index, default=default, comment=comment)


def string_index(index=False, default=None, comment=''):
    return Column(String(512), index=index, default=default, comment=comment)


def string(default=None, comment=''):
    return Column(String(1024), default=default, comment=comment)


def text(comment=''):
    return Column(Text, default=None, comment=comment)


def largebinary(comment=''):
    return Column(LargeBinary, default=None, comment=comment)


def mediumblob(comment=''):
    return Column(LargeBinary(65536), default=None, comment=comment)


def longblob(comment=''):
    return Column(LargeBinary(16777216), default=None, comment=comment)


def largebinary_dumps(item):
    return pickle.dumps(item)


def largebinary_loads(item):
    return pickle.loads(item)


def date_time(comment='日期'):
    return Column(DateTime, default=None, comment=comment)


def create_time(comment='创建时间'):
    return Column(DateTime, default=datetime.now, comment=comment)


def update_time(comment='更新时间'):
    return Column(DateTime, default=datetime.now, onupdate=datetime.now, comment=comment)


def id():
    return Column(Integer, primary_key=True, autoincrement=True, comment='主键')
